package com.yneusoft.manage.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.yneusoft.common.model.ResponseWrapper;
import com.yneusoft.common.tool.CommonTool;
import com.yneusoft.dao.entity.Department;
import com.yneusoft.dao.entity.DepartmentStaff;
import com.yneusoft.dao.entity.Staff;
import com.yneusoft.dao.entity.StaffState;
import com.yneusoft.dao.mapper.DepartmentMapper;
import com.yneusoft.dao.mapper.DepartmentStaffMapper;
import com.yneusoft.dao.mapper.StaffManageMapper;
import com.yneusoft.manage.aspect.StaffHttpAspect;
import com.yneusoft.manage.mapper.StaffManage;
import com.yneusoft.manage.model.param.*;
import com.yneusoft.manage.model.result.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class StaffManageService {
    /*
     * pc-manage下的
     * */
    @Resource
    private StaffManage staffManage;

    @Resource
    private StaffHttpAspect httpAspect;


    /*
     * dao层下面的
     * */
    @Resource
    private StaffManageMapper staffManageMapper;


    @Resource
    private DepartmentStaffMapper departmentStaffMapper;

    @Resource
    DepartmentMapper departmentMapper;

    @Resource
    GridFsOperations gridFsOperations;


    /*
     * 1、获取员工列表
     * @Param searchKey 搜索关键字
     * @Param id  员工状态id
     * @Param page 当前页
     * @Param pageSize 每页数
     * */
    public ResponseWrapper getStaffList(GetStaffListParam param){
        String searchKey = param.getSearchKey();
        Integer id = param.getId();
        Integer page = param.getPage();
        Integer pageSize = param.getPageSize();
        String str = "%" + searchKey + "%";
        int current = (page - 1) * pageSize;
        List<Map<String, Object>> staffList = staffManage.getStaffList(str, id, current, pageSize);
        List<GetStaffsListResult> getStaffLists = CommonTool.mapListToBeanList(staffList, GetStaffsListResult.class);
        GetStaffListResult getStaffList = new GetStaffListResult();
        int rowNumber = staffManage.getRowNumber(str, id, current, pageSize);
        getStaffList.setRowNumber(rowNumber);
        getStaffList.setList(getStaffLists);
        return ResponseWrapper.markSuccess(getStaffList);

    }

    /**
     * 2、获取员工状态列表
     *
     * @return 获取员工状态列表
     */
    public ResponseWrapper getStaffStateList() {
        List<GetStaffStateListResult> result= JSONArray.parseArray(JSON.toJSONString(StaffState.dataList
        )).toJavaList(GetStaffStateListResult.class);
        return ResponseWrapper.markSuccess(result);
    }


    /**
     * 3、【新增/修改】获取修改员工信息
     * @Param aid 员工aid
     * @return 返回员工修改信息
     */
    public ResponseWrapper getStaffInfo(UpdateStaffInfoParam param){
        GetStaffInfoResult getStaffInfo = new GetStaffInfoResult();
        GetFileResult getFileResult=new GetFileResult();
        LambdaQueryWrapper<Staff> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Staff::getAid,param.getAid());
        Staff staffList = staffManageMapper.selectOne(wrapper);
        if(staffList!=null){
            List<Map<String, Object>> staffDepartment = staffManage.getStaffDepartment(staffList.getAid());
            List<GetStaffDepartmentListResult> departmentLists = CommonTool.mapListToBeanList(staffDepartment, GetStaffDepartmentListResult.class);
            GridFSFile gridFsFile = gridFsOperations.findOne(Query.query(Criteria.where("_id").is(staffList.getEnclosureId())));
            if (gridFsFile!=null){
                getFileResult.setEnclosureId(staffList.getEnclosureId());
                getFileResult.setEnclosureName(gridFsFile.getFilename());
            }else {
                getFileResult.setEnclosureId(null);
                getFileResult.setEnclosureName(null);
            }
            getStaffInfo.setName(staffList.getName());
            getStaffInfo.setSex(staffList.getSex()==1);
            getStaffInfo.setPassword(staffList.getPassword());
            getStaffInfo.setPhone(staffList.getPhone());
            getStaffInfo.setIdNumber(staffList.getIdNumber());
            getStaffInfo.setFile(getFileResult);
            getStaffInfo.setList(departmentLists);
            return ResponseWrapper.markSuccess(getStaffInfo);

        }else {
            return ResponseWrapper.markCustomError("该员工不存在");
        }

    }

    /**
     * 4、校验手机号
     * @Param aid 员工aid
     * @Param phone 手机号
     * @return true(手机号存在) ，false(手机号不存在)
     */
    public ResponseWrapper getStaffPhoneList(CheckStaffPhoneParam param) {
        Integer aid = param.getAid();
        String phone = param.getPhone();
        CheckStaffPhoneResult checkStaffPhone = new CheckStaffPhoneResult();
        GetFileResult getFileResult=new GetFileResult();
        GetStaffInfoResult getStaffInfo;
        if(aid == null){
            if(StringUtils.isNotBlank(phone)){
                LambdaQueryWrapper<Staff> wrapper=new LambdaQueryWrapper<>();
                wrapper.eq(Staff::getPhone,phone);
                Staff staffList = staffManageMapper.selectOne(wrapper);
                getStaffInfo = new GetStaffInfoResult();
                if(staffList != null){
                    List<Map<String, Object>> staffDepartment = staffManage.getStaffDepartment(staffList.getAid());
                    List<GetStaffDepartmentListResult> departmentLists = CommonTool.mapListToBeanList(staffDepartment, GetStaffDepartmentListResult.class);
                    GridFSFile gridFsFile = gridFsOperations.findOne(Query.query(Criteria.where("_id").is(staffList.getEnclosureId())));
                    if (gridFsFile!=null){
                        getFileResult.setEnclosureId(staffList.getEnclosureId());
                        getFileResult.setEnclosureName(gridFsFile.getFilename());
                    }else {
                        getFileResult.setEnclosureId(null);
                        getFileResult.setEnclosureName(null);
                    }
                    getStaffInfo.setName(staffList.getName());
                    getStaffInfo.setSex(staffList.getSex()==1);
                    getStaffInfo.setPassword(staffList.getPassword());
                    getStaffInfo.setPhone(staffList.getPhone());
                    getStaffInfo.setIdNumber(staffList.getIdNumber());
                    getStaffInfo.setFile(getFileResult);
                    getStaffInfo.setList(departmentLists);
                    checkStaffPhone.setList(getStaffInfo);
                    checkStaffPhone.setIsExists(true);
                    return ResponseWrapper.markCustomSuccess("新增电话号码存在",checkStaffPhone);
                }else {
                    checkStaffPhone.setList(getStaffInfo);
                    checkStaffPhone.setIsExists(false);
                    return ResponseWrapper.markCustomSuccess("新增电话号码不存在",checkStaffPhone);
                }
            }else {
                return ResponseWrapper.markCustomError("电话号码为空");
            }
        }else {
            if(StringUtils.isNotBlank(phone)){
                LambdaQueryWrapper<Staff> wrapper=new LambdaQueryWrapper<>();
                wrapper.eq(Staff::getPhone,phone);
                Staff staffList = staffManageMapper.selectOne(wrapper);
                getStaffInfo = new GetStaffInfoResult();
                if(staffList != null){
                    List<Map<String, Object>> staffDepartment = staffManage.getStaffDepartment(staffList.getAid());
                    List<GetStaffDepartmentListResult> departmentLists = CommonTool.mapListToBeanList(staffDepartment, GetStaffDepartmentListResult.class);
                    GridFSFile gridFsFile = gridFsOperations.findOne(Query.query(Criteria.where("_id").is(staffList.getEnclosureId())));
                    if (gridFsFile!=null){
                        getFileResult.setEnclosureId(staffList.getEnclosureId());
                        getFileResult.setEnclosureName(gridFsFile.getFilename());
                    }else {
                        getFileResult.setEnclosureId(null);
                        getFileResult.setEnclosureName(null);
                    }
                    getStaffInfo.setName(staffList.getName());
                    getStaffInfo.setSex(staffList.getSex()==1);
                    getStaffInfo.setPassword(staffList.getPassword());
                    getStaffInfo.setPhone(staffList.getPhone());
                    getStaffInfo.setIdNumber(staffList.getIdNumber());
                    getStaffInfo.setFile(getFileResult);
                    getStaffInfo.setList(departmentLists);
                    checkStaffPhone.setList(getStaffInfo);
                    checkStaffPhone.setIsExists(true);
                    return ResponseWrapper.markCustomSuccess("修改电话号码存在",checkStaffPhone);
                }else {
                    checkStaffPhone.setList(getStaffInfo);
                    checkStaffPhone.setIsExists(false);
                    return ResponseWrapper.markCustomSuccess("修改电话号码不存在",checkStaffPhone);
                }
            }else {
                return ResponseWrapper.markCustomError("修改电话号码为空！");
            }
        }

    }

    /**
     * 5、校验身份证号
     *@Param aid 员工aid
     * @Param idNumber 身份证号
     * @return true(身份证号存在)，false(身份证号不存在)
     */
    public ResponseWrapper getStaffIdNumber(CheckStaffIdNumberParam param) {
        Integer aid =param.getAid();
        String idNumber = param.getIdNumber();
        GetFileResult getFileResult=new GetFileResult();
        CheckStaffIdNumberResult checkStaffIdNumber=new CheckStaffIdNumberResult();
        GetStaffInfoResult getStaffInfo;
        if (aid==null){
            if (StringUtils.isNotBlank(idNumber)){
                LambdaQueryWrapper<Staff> wrapper=new LambdaQueryWrapper<>();
                wrapper.eq(Staff::getIdNumber,idNumber);
                Staff staffList = staffManageMapper.selectOne(wrapper);
                getStaffInfo=new GetStaffInfoResult();
                if (staffList!=null){
                    List<Map<String, Object>> staffDepartment = staffManage.getStaffDepartment(staffList.getAid());
                    List<GetStaffDepartmentListResult> departmentLists = CommonTool.mapListToBeanList(staffDepartment, GetStaffDepartmentListResult.class);
                    GridFSFile gridFsFile = gridFsOperations.findOne(Query.query(Criteria.where("_id").is(staffList.getEnclosureId())));
                    if (gridFsFile!=null){
                        getFileResult.setEnclosureId(staffList.getEnclosureId());
                        getFileResult.setEnclosureName(gridFsFile.getFilename());
                    }else {
                        getFileResult.setEnclosureId(null);
                        getFileResult.setEnclosureName(null);
                    }
                    getStaffInfo.setName(staffList.getName());
                    getStaffInfo.setSex(staffList.getSex()==1);
                    getStaffInfo.setPassword(staffList.getPassword());
                    getStaffInfo.setPhone(staffList.getPhone());
                    getStaffInfo.setIdNumber(staffList.getIdNumber());
                    getStaffInfo.setFile(getFileResult);
                    getStaffInfo.setList(departmentLists);
                    checkStaffIdNumber.setList(getStaffInfo);
                    checkStaffIdNumber.setIsExists(true);
                    return ResponseWrapper.markCustomSuccess("新增身份证号存在",checkStaffIdNumber);
                }else {
                    checkStaffIdNumber.setIsExists(false);
                    checkStaffIdNumber.setList(getStaffInfo);
                    return ResponseWrapper.markCustomSuccess("新增身份证号不存在",checkStaffIdNumber);
                }
            }else {
                return ResponseWrapper.markCustomError("身份证号为空");
            }
        }else {
            if (StringUtils.isNotBlank(idNumber)){
                LambdaQueryWrapper<Staff> wrapper=new LambdaQueryWrapper<>();
                wrapper.eq(Staff::getIdNumber,idNumber).ne(Staff::getAid,aid);
                Staff staffList = staffManageMapper.selectOne(wrapper);
                getStaffInfo=new GetStaffInfoResult();
                if (staffList!=null){
                    List<Map<String, Object>> staffDepartment = staffManage.getStaffDepartment(staffList.getAid());
                    List<GetStaffDepartmentListResult> departmentLists = CommonTool.mapListToBeanList(staffDepartment, GetStaffDepartmentListResult.class);
                    GridFSFile gridFsFile = gridFsOperations.findOne(Query.query(Criteria.where("_id").is(staffList.getEnclosureId())));
                    if (gridFsFile!=null){
                        getFileResult.setEnclosureId(staffList.getEnclosureId());
                        getFileResult.setEnclosureName(gridFsFile.getFilename());
                    }else {
                        getFileResult.setEnclosureId(null);
                        getFileResult.setEnclosureName(null);
                    }
                    getStaffInfo.setName(staffList.getName());
                    getStaffInfo.setSex(staffList.getSex()==1);
                    getStaffInfo.setPassword(staffList.getPassword());
                    getStaffInfo.setPhone(staffList.getPhone());
                    getStaffInfo.setIdNumber(staffList.getIdNumber());
                    getStaffInfo.setFile(getFileResult);
                    getStaffInfo.setList(departmentLists);
                    checkStaffIdNumber.setList(getStaffInfo);
                    checkStaffIdNumber.setIsExists(true);
                    return ResponseWrapper.markCustomSuccess("修改身份证号存在",checkStaffIdNumber);
                }else {
                    checkStaffIdNumber.setIsExists(false);
                    checkStaffIdNumber.setList(getStaffInfo);
                    return ResponseWrapper.markCustomSuccess("修改身份证号不存在",checkStaffIdNumber);
                }
            }else {
                return ResponseWrapper.markCustomError("修改身份证号为空");
            }
        }
    }

    /*
     * 6、【新增/修改员工】获取员工所在部门
     * @Param aid 员工aid
     * */

    public ResponseWrapper getStaffDepartment(GetStaffDepartmentListParam param) {
        LambdaQueryWrapper<Department> wrapper=new LambdaQueryWrapper<>();
        if (param.getAid() == null){
            wrapper.select(Department::getAid,Department::getName);
            List<Department> list= departmentMapper.selectList(wrapper);
            List<GetStaffDepartmentListResult> result=JSONArray.parseArray(JSON.toJSONString(list)).toJavaList(GetStaffDepartmentListResult.class);
            return ResponseWrapper.markSuccess(result);
        }else {
            List<Map<String, Object>> staffDepartment = staffManage.getStaffDepartmentName(param.getAid());
            List<GetStaffDepartmentListResult> departmentListResults =CommonTool.mapListToBeanList(staffDepartment,GetStaffDepartmentListResult.class);
            return ResponseWrapper.markSuccess(departmentListResults);
        }
    }

    /*
     * 7、【新增 / 修改员工】新增/修改员工信息 错  List<SaveStaffDepartment> argumentResolvers
     * */
    @Transactional
    public ResponseWrapper saveStaff(SaveStaffParam param){
        List<Integer> id =param.getDepartmentList();
        Integer aid = param.getAid();
        String name = param.getName();
        boolean sex = param.getSex();
        String idNumber = param.getIdNumber();
        String password = param.getPassword();
        String phone = param.getPhone();
        Staff staff = new Staff();
        staff.setName(name);
        staff.setIdNumber(idNumber);
        staff.setPhone(phone);
        staff.setPassword(password);
        staff.setSex(sex ? 1:0);
        staff.setEnclosureId(param.getEnclosureId());
        staff.setStateId(param.getStateId());
        staff.setStateName(param.getStateName());

        if (aid == null){
            String jobNumber = httpAspect.getJobNumber();
            staff.setJobNumber(jobNumber);
            int result = staffManageMapper.insert(staff);
            int result2=0;
            LambdaQueryWrapper<Staff> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Staff::getJobNumber,jobNumber);
            Staff staff1 = staffManageMapper.selectOne(wrapper);

            for (Integer integer : id) {
                LambdaQueryWrapper<DepartmentStaff> wrapper1 = new LambdaQueryWrapper<>();
                DepartmentStaff staff2 = departmentStaffMapper.selectOne(wrapper1.orderByDesc(DepartmentStaff::getAid).last("limit 1"));
                DepartmentStaff departmentStaff = new DepartmentStaff();
                departmentStaff.setAid((staff2.getAid()+1));
                departmentStaff.setStaffAid(staff1.getAid());
                departmentStaff.setDepartmentAid(integer);
                result2 = departmentStaffMapper.insert(departmentStaff);
            }
            if(result > 0 && result2 >0){
                return ResponseWrapper.markCustomSuccess("新增成功");
            }else {
                return ResponseWrapper.markCustomSuccess("新增失败");
            }
        }else {
            int r,r1,r2=0;
            staff.setAid(aid);
            r = staffManageMapper.updateById(staff);
            LambdaQueryWrapper<DepartmentStaff> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(DepartmentStaff::getStaffAid,aid);
            r1 = departmentStaffMapper.delete(wrapper2);
            for (Integer integer : id) {
                LambdaQueryWrapper<DepartmentStaff> wrapper1 = new LambdaQueryWrapper<>();
                DepartmentStaff staff2 = departmentStaffMapper.selectOne(wrapper1.orderByDesc(DepartmentStaff::getAid).last("limit 1"));
                DepartmentStaff departmentStaff = new DepartmentStaff();
                departmentStaff.setAid((staff2.getAid()+1));
                departmentStaff.setStaffAid(aid);
                departmentStaff.setDepartmentAid(integer);
                r2 = departmentStaffMapper.insert(departmentStaff);
            }

            if (r>0||(r1>0&&r2>0)){
                return ResponseWrapper.markCustomSuccess("修改成功");
            }else {
                return ResponseWrapper.markCustomSuccess("修改失败");
            }

            /*
            * 先删除部门员工表中staff_aid=aid的数据，然后插入在部门员工表中插入数据(department_aid=添加部门的aid)
            * */

        }
    }

    /**
     * 8、【离职/重新入职】更改员工状态
     *
     * @return 修改成功或失败
     */
    public ResponseWrapper updateStaffStateById(UpdateStaffStateParam param) {
        LambdaUpdateWrapper<Staff> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Staff::getAid,param.getAid()).set(Staff::getStateId,param.getStateId()).set(Staff::getStateName,param.getStateName());
        int i = staffManageMapper.update(null, wrapper);
        if (i > 0) {
            return ResponseWrapper.markSuccess();
        } else
            return ResponseWrapper.markError();
    }

}